package com.xzzz.backend.bsms.server.rbac.sys.dict.name;

import cn.hutool.core.map.MapUtil;
import com.xzzz.backend.bsms.server.rbac.sys.dict.DictService;
import com.xzzz.backend.bsms.server.rbac.sys.dict.pojo.DictEntity;
import com.xzzz.backend.bsms.server.rbac.sys.dict.pojo.DictReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 字典缓存
 */
@Slf4j
@Component
public class DictCache implements CommandLineRunner {

    /**
     * 字典缓存: groupId > dictId > DictEntity
     */
    private static final HashMap<String, Map<String, DictEntity>> dictCache = new HashMap<>();

    @Autowired
    private DictService dictService;

    @Override
    public void run(String... args) {
        refresh();
    }

    public void refresh() {
        List<DictEntity> dictAll = dictService.listAll(new DictReq());
        dictCache.clear();
        Map<String, List<DictEntity>> dictMap = dictAll.stream().collect(Collectors.groupingBy(DictEntity::getGroupId));
        dictMap.forEach((dictId, childDict) -> {
            Map<String, DictEntity> dictChildMap = childDict.stream().collect(Collectors.toMap(DictEntity::getDictId, dict -> dict));
            dictCache.put(dictId, dictChildMap);
        });
        log.info("字典缓存完成");
    }

    /**
     * 刷新缓存
     */
    public void refresh(DictEntity dict) {
        Map<String, DictEntity> childDict = dictCache.get(dict.getGroupId());
        childDict.put(dict.getDictId(), dict);
    }

    /**
     * 获取缓存字典
     *
     * @param groupId  字典ID
     * @param dictId 字典值ID
     */
    public String getDictName(String groupId, String dictId) {
        Map<String, DictEntity> childDict = dictCache.get(groupId);
        if (MapUtil.isNotEmpty(childDict)) {
            DictEntity dictEntity = childDict.get(dictId);
            if (dictEntity != null) {
                return dictEntity.getDictName();
            }
        }
        return "";
    }
}
